package com.cloud.adrian.novel.author.config;

import com.cloud.adrian.novel.author.manager.chache.AuthorInfoCacheManager;
import com.cloud.adrian.novel.author.novel.dto.AuthorInfoDto;
import com.cloud.adrian.novel.common.auth.JwtUtils;
import com.cloud.adrian.novel.common.auth.UserHolder;
import com.cloud.adrian.novel.common.constant.ErrorCodeEnum;
import com.cloud.adrian.novel.common.constant.SystemConfigConstants;
import com.cloud.adrian.novel.config.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;

/**
 * 认证授权 拦截器：为了注入其它的 Spring beans，
 * 需要通过 @Component 注解将该拦截器注册到 Spring 上下文
 * @Author: xiangguiliang
 * @version: 1.0
 * @since: 2024/05/30
 */
@Component
@RequiredArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {
    private final AuthorInfoCacheManager authorInfoCacheManager;

    @SuppressWarnings("NullableProblems")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取登录的jwt
        String token = request.getHeader(SystemConfigConstants.HTTP_AUTH_HEADER_NAME);

        // 验证token是否存在
        if (!StringUtils.hasText(token)) {
            throw new BusinessException(ErrorCodeEnum.USER_LOGIN_EXPIRED);
        }

        // 通过jwt解析token
        Long userId = JwtUtils.parseToken(token, SystemConfigConstants.NOVEL_FRONT_KEY);
        if (Objects.isNull(userId)) {
            throw new BusinessException(ErrorCodeEnum.USER_LOGIN_EXPIRED);
        }
        // 查询作家信息
        AuthorInfoDto author = authorInfoCacheManager.getAuthor(userId);
        if (Objects.isNull(author)) {
            // 当前用户不是作家，无权访问
            throw new BusinessException(ErrorCodeEnum.USER_UN_AUTH);
        }

        // 设置作家信息到当前线程中
        UserHolder.setUserId(userId);
        UserHolder.setAuthorId(author.getId());
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    /**
     * handler 执行后调用，出现异常不调用
     */
    @SuppressWarnings("NullableProblems")
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * DispatcherServlet 完全处理完请求后调用，出现异常照常调用
     */
    @SuppressWarnings("NullableProblems")
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // 清理当前线程保存的用户数据
        UserHolder.clear();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
